import { reactive, ref } from "vue";
import { get } from "lodash-es";
import {
  getNotesByPurchaseId,
  createTradeInNote,
} from "@/api/purchase/purchase.api";
import { PurchaseNote } from "@/types/model/purchase/vos/tradeinOrder.vo";
export const useNote = () => {
  const createPurchaseNoteForm = reactive({
    note: "",
  });
  const getPurchaseNotesLoading = ref<boolean>(false);
  const purchaseNotesList = ref<PurchaseNote[]>([]);

  const handleGetPurchaseNotes = async (purchaseId: string) => {
    getPurchaseNotesLoading.value = true;
    try {
      const result = await getNotesByPurchaseId(purchaseId);
      purchaseNotesList.value = get(result, "result") || [];
    } finally {
      getPurchaseNotesLoading.value = false;
    }
  };

  const handleAddTradeInNote = async (purchaseId: string) => {
    const params = {
      purchaseId,
      note: createPurchaseNoteForm.note,
    };
    getPurchaseNotesLoading.value = true;
    try {
      await createTradeInNote(params);
      createPurchaseNoteForm.note = "";
      await handleGetPurchaseNotes(purchaseId);
    } finally {
      getPurchaseNotesLoading.value = false;
    }
  };

  return {
    createPurchaseNoteForm,
    getPurchaseNotesLoading,
    purchaseNotesList,
    handleAddTradeInNote,
    handleGetPurchaseNotes,
  };
};
